<template>
  <div>
    <div style="display: flex; justify-content: space-between">
      <div>
        <el-input placeholder="员工名称" size="mini" prefix-icon="el-icon-search" style="width: 300px" v-model="keword"
          clearable></el-input>
        <el-button icon="el-icon-search" size="mini" type="primary" style="margin-left: 10px" @click="initEmps()">搜索
        </el-button>
        <el-button icon="el-icon-caret-bottom" size="mini" type="primary">高级搜索</el-button>
      </div>
      <div>
        <el-upload
          style="display: inline-flex;margin-right: 10px;"
          action="/emp/basic/importData"
          multiple
          :limit="3"
          :show-file-list= "false"
          :before-upload="beforeUpload"
          :on-success= "onSuccess"
          :on-error="onError">
          <el-button :icon="improtDataIcon" :disabled="importDataBtnDisabled" size="mini" type="success">{{importDataBtnText}}</el-button>
        </el-upload>
        
        <el-button icon="el-icon-download" size="mini" type="success" @click="exportData()">导出数据</el-button>
        <el-button icon="el-icon-plus" size="mini" type="primary" @click="showAddEmpView()">添加员工</el-button>
      </div>
    </div>
    <div style="margin-top: 10px">
      <el-table :data="emps" stripe border style="width: 100%" size="mini" v-loading="loading"
        element-loading-text="正在加载数据...">
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column fixed align="center" prop="name" label="姓名" width="90">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <p>姓名: {{ scope.row.name }}</p>
              <p>住址: {{ scope.row.address }}</p>
              <div slot="reference" class="name-wrapper" style="cursor: pointer">
                <el-tag size="medium">{{ scope.row.name }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="workId" label="工号" width="80">
        </el-table-column>
        <el-table-column prop="birthday" label="出生日期" width="90">
        </el-table-column>
        <el-table-column prop="idCard" label="证件号码" width="180">
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="50">
        </el-table-column>
        <el-table-column prop="wedlock" label="婚姻状况" width="70">
        </el-table-column>
        <el-table-column prop="nation.name" label="名族" width="70">
        </el-table-column>
        <el-table-column prop="nativePlace" label="籍贯" width="70">
        </el-table-column>
        <el-table-column prop="politicsStatus.name" label="政治面貌" width="90">
        </el-table-column>
        <el-table-column prop="email" label="电子邮件" width="160">
        </el-table-column>
        <el-table-column prop="phone" label="电话号码" width="120">
        </el-table-column>
        <!-- <el-table-column prop="address" label="联系地址" width="200">
        </el-table-column> -->
        <el-table-column prop="department.name" label="所属部门" width="90">
        </el-table-column>
        <el-table-column prop="position.name" label="职位" width="90">
        </el-table-column>
        <el-table-column prop="jobLevel.name" label="职称" width="120">
        </el-table-column>
        <el-table-column prop="engageForm" label="聘用形式" width="90">
        </el-table-column>
        <el-table-column prop="beginDate" label="入职日期" width="90">
        </el-table-column>
        <el-table-column prop="conversionTime" label="转正日期" width="90">
        </el-table-column>
        <el-table-column prop="beginContract" label="合同起始日期" width="120">
        </el-table-column>
        <el-table-column prop="endContract" label="合同截止日期" width="120">
        </el-table-column>
        <el-table-column label="合同期限" width="90">
          <template slot-scope="scope">
            <el-tag size="mini" type="success">{{ scope.row.contractTerm }}年</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="tiptopDegree" label="最高学历">
        </el-table-column>
        <el-table-column prop="school" label="毕业院校" width="150">
        </el-table-column>
        <el-table-column prop="specialty" label="所属专业" width="150">
        </el-table-column>
        <el-table-column prop="birthday" label="操作" width="260" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="showEditEmpView(scope.row)">编辑</el-button>
            <el-button size="mini" type="primary" @click="showInfo(scope.row)">查看高级资料</el-button>
            <el-button size="mini" type="danger" @click="deleteEmps(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="display: flex; justify-content: flex-end">
        <el-pagination background @size-change="sizeChange" @current-change="currentChange"
          layout="sizes, prev, pager, next, jumper, ->, total, slot" :total="total">
        </el-pagination>
      </div>
    </div>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="70%">
      <el-form ref="empForm" label-width="auto" :rules="rules" :model="emp">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="姓名:" prop="name">
              <el-input size="mini" v-model="emp.name" placeholder="姓名"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="性别:" prop="gender">
              <el-radio-group v-model="emp.gender">
                <el-radio label="男">男</el-radio>
                <el-radio label="女">女</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="出生日期:" prop="birthday">
              <el-date-picker v-model="emp.birthday" size="mini" type="date" value-format="yyyy-MM-dd"
                placeholder="选择日期" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="政治面貌:" prop="politicId">
              <el-select v-model="emp.politicId" placeholder="请选择政治面貌" size="mini" style="width: 100%">
                <el-option v-for="(politicsStatusItem, index) in politicsStatus" :key="index"
                  :label="politicsStatusItem.name" :value="politicsStatusItem.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="名族:" prop="nationId">
              <el-select v-model="emp.nationId" placeholder="请选择名族" size="mini" style="width: 100%">
                <el-option v-for="(nationItem, index) in nation" :key="index" :label="nationItem.name"
                  :value="nationItem.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="籍贯:" prop="nativePlace">
              <el-input size="mini" v-model="emp.nativePlace" placeholder="籍贯"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="电子邮箱:" prop="email">
              <el-input size="mini" v-model="emp.email" placeholder="电子邮箱"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="联系地址:" prop="address">
              <el-input size="mini" v-model="emp.address" placeholder="联系地址"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="职位:" prop="posId">
              <el-select v-model="emp.posId" placeholder="请选择职位" size="mini" style="width: 100%">
                <el-option v-for="(positionItem, index) in position" :key="index" :label="positionItem.name"
                  :value="positionItem.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="职称:" prop="jobLevelId">
              <el-select v-model="emp.jobLevelId" placeholder="请选择职称" size="mini" style="width: 100%">
                <el-option v-for="(jobLevelItem, index) in jobLevel" :key="index" :label="jobLevelItem.name"
                  :value="jobLevelItem.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所属部门:" prop="departmentId">
              <el-popover
                placement="right"
                title="请选择部门"
                width="200"
                trigger="manual"
                v-model="popVisible">
                  <el-tree :data="department" :props="defaultProps" @node-click="handleNodeClick" default-expand-all ></el-tree>
                <el-input slot="reference" size="mini" @click.native="showDepartmentView" v-model="inputDepName" placeholder="所属部门" readonly class="departmentId-input"></el-input>
              </el-popover>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="联系电话:" prop="phone">
              <el-input size="mini" v-model="emp.phone" placeholder="联系电话"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="工号:" prop="workId">
              <el-input size="mini" v-model="emp.workId" placeholder="工号" disabled></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="学历:" prop="tiptopDegree">
              <el-select v-model="emp.tiptopDegree" placeholder="最高学历" size="mini" style="width: 100%">
                <el-option label="博士" value="博士"></el-option>
                <el-option label="硕士" value="硕士"></el-option>
                <el-option label="本科" value="本科"></el-option>
                <el-option label="大专" value="大专"></el-option>
                <el-option label="高中" value="高中"></el-option>
                <el-option label="初中" value="初中"></el-option>
                <el-option label="小学" value="小学"></el-option>
                <el-option label="其他" value="其他"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="毕业院校:" prop="school">
              <el-input size="mini" v-model="emp.school" placeholder="毕业院校"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="专业名称:" prop="specialty">
              <el-input size="mini" v-model="emp.specialty" placeholder="专业名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="入职日期:" prop="beginDate">
              <el-date-picker v-model="emp.beginDate" size="mini" type="date" value-format="yyyy-MM-dd"
                placeholder="选择日期" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="转正日期:" prop="conversionTime">
              <el-date-picker v-model="emp.conversionTime" size="mini" type="date" value-format="yyyy-MM-dd"
                placeholder="选择日期" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="合同起始日期:" prop="beginContract">
              <el-date-picker v-model="emp.beginContract" size="mini" type="date" value-format="yyyy-MM-dd"
                placeholder="选择日期" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="合同截止日期:" prop="endContract">
              <el-date-picker v-model="emp.endContract" size="mini" type="date" value-format="yyyy-MM-dd"
                placeholder="选择日期" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="身份证号码:" prop="idCard">
              <el-input size="mini" v-model="emp.idCard" placeholder="身份证号码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="聘用形式:" prop="engageForm">
              <el-radio-group v-model="emp.engageForm" style="width: 100%">
                <el-radio label="劳动合同">劳动合同</el-radio>
                <el-radio label="劳务合同">劳务合同</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="婚姻状况:" prop="wedlock">
              <el-radio-group v-model="emp.wedlock" style="width: 100%">
                <el-radio label="已婚">已婚</el-radio>
                <el-radio label="未婚">未婚</el-radio>
                <el-radio label="离异">离异</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="doAddEmp">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    components: {},
    data() {
      return {
        importDataBtnDisabled: false,
        importDataBtnText: "导入数据",
        improtDataIcon: "el-icon-upload2",
        title: '',
        popVisible: false,
        emps: [],
        keword: "",
        total: 0,
        pageNum: 1,
        pageSize: 10,
        loading: true,
        dialogVisible: false,
        jobLevel: [],
        department: [],
        position: [],
        politicsStatus: [],
        nation: [],
        emp: {
          id: null,
          name: "",
          gender: "",
          birthday: "",
          politicId: null,
          idCard: "",
          wedlock: "",
          nationId: null,
          nativePlace: "",
          email: "",
          phone: "",
          address: "",
          departmentId: null,
          jobLevelId: null,
          posId: null,
          engageForm: "",
          tiptopDegree: "",
          specialty: "",
          school: "",
          beginDate: "",
          workId: "",
          contractTerm: null,
          conversionTime: "",
          notWorkDate: null,
          beginContract: "",
          endContract: "",
          workAge: null,
        },
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        inputDepName: '',
        rules: {
          name: [{ required: true, message: "请输入员工姓名", trigger: ['blur', 'change'] }],
          gender: [{ required: true, message: "请选择员工性别", trigger: ['blur', 'change'] }],
          birthday: [{ required: true, message: "请输入员工出生日期", trigger: ['blur', 'change'] }],
          politicId: [{ required: true, message: "请选择政治面貌", trigger: ['blur', 'change'] }],
          nationId: [{ required: true, message: "请选择名族", trigger: ['blur', 'change'] }],
          nativePlace: [{ required: true, message: "请输入籍贯", trigger: ['blur', 'change'] }],
          email: [{ required: true, message: "请输入电子邮箱", trigger: ['blur', 'change'] },{type:'email',message:"邮箱格式不正确!",trigger: ['blur', 'change']}],
          address: [{ required: true, message: "请输入联系地址", trigger: ['blur', 'change'] }],
          posId: [{ required: true, message: "请选择职位", trigger: ['blur', 'change'] }],
          jobLevelId: [{ required: true, message: "请选择职称", trigger: ['blur', 'change'] }],
          departmentId: [{ required: true, message: "请选择所属部门", trigger: ['blur', 'change'] }],
          phone: [{ required: true, message: "请填写联系电话", trigger: ['blur', 'change'] }],
          tiptopDegree: [{ required: true, message: "请选择学历", trigger: ['blur', 'change'] }],
          school: [{ required: true, message: "请填写毕业院校", trigger: ['blur', 'change'] }],
          specialty: [{ required: true, message: "请填写专业名称", trigger: ['blur', 'change'] }],
          beginDate: [{ required: true, message: "请选择入职日期", trigger: ['blur', 'change'] }],
          conversionTime: [{ required: true, message: "请选择转正日期", trigger: ['blur', 'change'] }],
          beginContract: [{ required: true, message: "请选择合同开始日期", trigger: ['blur', 'change'] }],
          endContract: [{ required: true, message: "请选择合同结束日期", trigger: ['blur', 'change'] }],
          idCard: [{ required: true, message: "请输入身份证号码", trigger: ['blur', 'change'] },{pattern:/^[1-9]\d{7}((0\d)|bai(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/,message:"身份证号码格式不正确!",trigger: ['blur', 'change']}],
          engageForm: [{ required: true, message: "请选择聘用形式", trigger: ['blur', 'change'] }],
          wedlock: [{ required: true, message: "请选择婚姻状况", trigger: ['blur', 'change'] }],
        }
      };
    },
    methods: {
      /**
       * 文件上传失败的钩子函数
       */
      onError() {
        this.importDataBtnText = "导入数据";
        this.improtDataIcon = "el-icon-upload2"
        this.importDataBtnDisabled = false;
      },
      /**
       * 文件上传成功的钩子函数
       */
      onSuccess() {
        this.importDataBtnText = "导入数据";
        this.improtDataIcon = "el-icon-upload2"
        this.importDataBtnDisabled = false;
      },
      /**
       * 文件上传之前的钩子函数 
       */
      beforeUpload() {
        this.importDataBtnText = "正在导入";
        this.improtDataIcon = "el-icon-loading"
        this.importDataBtnDisabled = true;
      },
      /** 文件下载 */
      exportData() {
        window.open("/emp/basic/exportData",'_parent')
      },
      /**
       * 新增用户之前初始化form
       */
      emptyEmp() {
        this.emp =  {
          id: null,
          name: "",
          gender: "",
          birthday: "",
          politicId: null,
          idCard: "",
          wedlock: "",
          nationId: null,
          nativePlace: "",
          email: "",
          phone: "",
          address: "",
          departmentId: null,
          jobLevelId: null,
          posId: null,
          engageForm: "",
          tiptopDegree: "",
          specialty: "",
          school: "",
          beginDate: "",
          workId: "",
          contractTerm: null,
          conversionTime: "",
          notWorkDate: null,
          beginContract: "",
          endContract: "",
          workAge: null,
        }
        this.inputDepName = "";
      },
      /**
       * 删除员工信息
       */
      deleteEmps(data) {
        let ids = new Array();
        ids.push(data.id);
        this.$confirm("此操作将永久删除【" + data.name + "】员工, 是否继续?",'提示',{
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.deleteRequset("/emp/basic/", ids).then((resp) => {
            if (resp) {
              this.initEmps();
            }
          });
        }).catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
      },
      /**
       * 添加或者修改员工信息
       */
      doAddEmp() {
        if(this.emp.id) {//如果有id,就做更新操作
          this.$refs['empForm'].validate(valid=>{
            if(valid) {
              this.dialogVisible = false;
              this.putRequset("/emp/basic/",this.emp).then(resp => {
                if(resp) {
                  this.initEmps();
                }
              })
            }
          })
        }else {//没有id做更新操作
          this.$refs['empForm'].validate(valid=>{
            if(valid) {
              this.dialogVisible = false;
              this.postRequset("/emp/basic/",this.emp).then(resp => {
                if(resp) {
                  this.initEmps();
                }
              })
            }
          })
        }
      },
      /**
       * 部门树的回调函数
       */
      handleNodeClick(data) {
        this.popVisible = !this.popVisible;
        this.inputDepName = data.name;
        this.emp.departmentId = data.id;
      },
      /**
       * 修改或新增时点击"所属部门时的事件"
       */
      showDepartmentView() {
        this.popVisible = !this.popVisible;
      },
      /**
       * 点击职位,职称时初始化职位职称信息
       */
      initJob() {
        this.getRequset("/emp/basic/getJobLevel").then((resp) => {
          if (resp) {
            this.jobLevel = resp;
          }
        });
        this.getRequset("/emp/basic/getPositions").then((resp) => {
          if (resp) {
            this.position = resp;
          }
        });
      },
      /**
       * 初始化名族,政治面貌以及部门树的信息
       */
      initSelect() {
        if (!window.sessionStorage.getItem("nation")) {
          this.getRequset("/emp/basic/getNations").then((resp) => {
            if (resp) {
              window.sessionStorage.setItem("nation", JSON.stringify(resp));
              this.nation = resp;
            }
          });
        } else {
          this.nation = JSON.parse(window.sessionStorage.getItem("nation"));
        }
        if (!window.sessionStorage.getItem("politicsStatus")) {
          this.getRequset("/emp/basic/getPoliticsStatus").then((resp) => {
            if (resp) {
              window.sessionStorage.setItem("politicsStatus", JSON.stringify(resp));
              this.politicsStatus = resp;
            }
          });
        } else {
          this.politicsStatus = JSON.parse(window.sessionStorage.getItem("politicsStatus"));
        }
        if (!window.sessionStorage.getItem("department")) {
          this.getRequset("/emp/basic/getDepartments").then((resp) => {
            if (resp) {
              window.sessionStorage.setItem("department", JSON.stringify(resp));
              this.department = resp;
            }
          });
        } else {
          this.department = JSON.parse(window.sessionStorage.getItem("department"));
        }
      },
      /**
       * 从服务器获得自增长的工号
       */
      getWordID() {
        this.getRequset("/emp/basic/getMaxWorkID").then(resp => {
          if (resp) {
            console.log(resp)
            this.emp.workId = resp.obj;
          }
        })
      },
      /**
       * 点击添加员工按钮时的事件
       */
      showAddEmpView() {
        this.title = "添加员工"
        this.dialogVisible = true;
        this.initJob();
        this.getWordID();
      },
      /**
       * 点击编辑时的事件
       */
      showEditEmpView(data) {
        this.emptyEmp();
        this.inputDepName = data.department.name;
        this.title = "编辑员工信息";
        this.emp = data;
        this.dialogVisible = true;
      },
      /**
       * 初始化员工列表信息
       */
      initEmps() {
        this.loading = true;
        this.getRequset(
          "/emp/basic/?pageNum=" +
          this.pageNum +
          "&pageSize=" +
          this.pageSize +
          "&keyword=" +
          this.keword
        )
          .then((resp) => {
            if (resp) {
              this.emps = resp.list;
              this.total = resp.total;
            }
          })
          .finally(() => {
            this.loading = false;
          });
      },
      /**
       * 改变当前页时的事件
       */
      currentChange(currentPage) {
        this.pageNum = currentPage;
        this.initEmps();
      },
      /**
       * 改变每页所显示数据多少的事件
       */
      sizeChange(pageSize) {
        this.pageSize = pageSize;
        this.initEmps();
      },
    },
    mounted() {
      this.initEmps();
      this.initSelect();
    },
  };
</script>
<style>
.departmentId-input .el-input__inner {
    cursor: pointer;
}
</style>